library item_count_number_button;

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

typedef CounterChangeCallback = void Function(num value, bool isAdd);
typedef IncrementInterceptor = bool Function();

class CountNumberButton extends StatefulWidget {
  CountNumberButton(
      {super.key,
      required this.initialValue,
      required this.minValue,
      required this.maxValue,
      required this.onChanged,
      this.colorActive,
      this.colorInactive,
      this.colorBg,
      this.textStyle,
      this.step = 1,
      this.width = 150,
      this.height = 46,
      this.maxLength,
      this.incrementInterceptor,
      this.numberEditable = false})
      : assert(maxValue > minValue),
        assert(initialValue >= minValue && initialValue <= maxValue),
        assert(step > 0);

  final CounterChangeCallback onChanged;
  final IncrementInterceptor? incrementInterceptor;

  ///min value user can pick
  final num minValue;

  ///max value user can pick
  final num maxValue;

  ///Currently selected integer value
  final num initialValue;

  final num step;

  final int? maxLength;

  // 可点击的颜色
  Color? colorActive;

  // 不可点击的颜色
  Color? colorInactive;

  // 背景颜色
  Color? colorBg;

  /// text style
  TextStyle? textStyle;

  bool numberEditable;

  final double width, height;

  static const double iconThickness = 4;

  @override
  State<CountNumberButton> createState() => _CountNumberButtonState();
}

class _CountNumberButtonState extends State<CountNumberButton> {
  double get editNumberWidth => widget.width - (widget.height * 2);

  double get iconWidth => widget.height * 0.65;

  Color get buttonActiveColor => widget.colorActive ?? Colors.amber;

  Color get buttonInactiveColor => widget.colorInactive ?? Colors.grey;

  bool get isMaxLimit => widget.initialValue >= widget.maxValue;

  bool get isMinLimit => widget.initialValue <= widget.minValue;

  final TextEditingController _controller = TextEditingController();

  @override
  void initState() {
    _controller.text = widget.initialValue.toString();
    super.initState();
  }

  @override
  void didUpdateWidget(CountNumberButton oldWidget) {
    super.didUpdateWidget(oldWidget);
    // 如果初始值发生变化，更新 TextEditingController 的文本
    if (oldWidget.initialValue != widget.initialValue) {
      _controller.text = widget.initialValue.toString();
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  void valueChanged(num value, {bool? isAdd}) {
    _controller.text = value.toString();
    widget.onChanged(value, isAdd == true);
  }

  void _incrementCounter() {
    if(!(widget.incrementInterceptor?.call() ?? false)) {
      if (widget.initialValue + widget.step <= widget.maxValue) {
        valueChanged(widget.initialValue + widget.step, isAdd: true);
      } else {
        setState(() {
          // 刷新页面
        });
      }
    } else {
      if (widget.initialValue + widget.step <= widget.maxValue) {
        valueChanged(widget.initialValue, isAdd: true);
      } else {
        setState(() {
          // 刷新页面
        });
      }
    }

  }

  void _decrementCounter() {
    debugPrint("_decrementCounter ${widget.initialValue} ${widget.step}");
    if (widget.initialValue - widget.step >= widget.minValue) {
      valueChanged((widget.initialValue - widget.step));
    } else {
      setState(() {
        // 刷新页面
      });
    }
  }

  void _updateCounter(int? inputCounter) {
    num counter = inputCounter ?? widget.minValue;
    if (counter < widget.minValue) {
      counter = widget.minValue;
    } else if (counter > widget.maxValue) {
      counter = widget.maxValue;
    }
    valueChanged(counter);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
          color: widget.colorBg ?? Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(widget.height))),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisSize: MainAxisSize.min,
        children: [
          GestureDetector(
            onTap: _decrementCounter,
            child: SizedBox(
              width: widget.height,
              height: widget.height,
              child: Container(
                decoration: BoxDecoration(
                    color: isMinLimit ? buttonInactiveColor : buttonActiveColor,
                    shape: BoxShape.circle),
                child: Center(
                  child: Container(
                    width: iconWidth,
                    height: CountNumberButton.iconThickness,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ),
          Container(
            alignment: Alignment.center,
            height: widget.height,
            width: editNumberWidth,
            child: TextField(
              controller: _controller,
              maxLength: widget.maxLength,
              enabled: widget.numberEditable,
              inputFormatters: [FilteringTextInputFormatter.digitsOnly],
              keyboardType:
                  const TextInputType.numberWithOptions(decimal: false),
              textAlign: TextAlign.center,
              decoration: const InputDecoration(
                border: InputBorder.none,
                counterText: '',
              ),
              onChanged: (value) {
                var tryParse = int.tryParse(value);
                _updateCounter(tryParse);
              },
              style: widget.textStyle ??
                  const TextStyle(
                    fontSize: 20.0,
                  ),
            ),
          ),
          GestureDetector(
            onTap: _incrementCounter,
            child: SizedBox(
              width: widget.height,
              height: widget.height,
              child: Container(
                padding: EdgeInsets.all(8.w),
                decoration: BoxDecoration(
                    color: isMaxLimit ? buttonInactiveColor : buttonActiveColor,
                    shape: BoxShape.circle),
                child: Stack(
                  alignment: Alignment.center,
                  // Center alignment for the cross
                  children: [
                    // 横线
                    Container(
                      width: iconWidth, // 横线的宽度
                      height: CountNumberButton.iconThickness, // 横线的高度
                      color: Colors.white, // 横线的颜色
                    ),
                    // 竖线
                    Container(
                      width: CountNumberButton.iconThickness, // 竖线的宽度
                      height: iconWidth, // 竖线的高度
                      color: Colors.white, // 竖线的颜色
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
